package com.zb.rpc.client;

import com.zb.rpc.client.codec.Codec;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public abstract class AbstractRpcClient implements RpcClient {

    private List<Interceptor> interceptors;

    private Codec codec;

    private Map<String, Message> invokeTable = new ConcurrentHashMap<>();

    public <T> ResponseFuture<T> invoke(String funcId, Message message) {
        // 执行拦截器
        if (this.interceptors != null) {
            interceptors.forEach(interceptor -> interceptor.beforeRequest(message));
        }
        return doInvoke(funcId, message, 5, TimeUnit.SECONDS);
    }

    public <T> ResponseFuture<T> doInvoke(String funcId, Message message, long timeout, TimeUnit unit) {
        ResponseFuture<T> responseFuture = new ResponseFuture<>();
        // 生成requestId
        String requestId = UUID.randomUUID().toString();
        // 设置metadata
        List<Metadata> metadataList = message.getMetadataList() == null ? new ArrayList<>() : message.getMetadataList();
        Metadata<String> metadata = new Metadata<>(100000, requestId);
        metadataList.add(metadata);
        Metadata<String> funcIdMeta = new Metadata<>(100001, funcId);
        metadataList.add(funcIdMeta);
        // 编码
        byte[] bytes = codec.encode(message);
        // 发送请求
        send(bytes);
        return responseFuture;
    }

    protected abstract void send(byte[] bytes);

    protected abstract void handleResponse();
}
